﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Xml.Linq;
using VCLib.Network.HTTPServers;
using VideoCarousel.Entity;

namespace VideoCarousel.Control
{
    internal class HttpInput
    {
        private int port;
        private System.Net.IPAddress[] iPAddresses;

        public HttpInput(System.Net.IPAddress[] iPAddresses,int port) 
        {
            this.port = port;
            this.iPAddresses = iPAddresses;
            
        }
        public VCLib.Network.HTTPServers.HttpService WebHttpService { get; set; }
        public void Init()
        {

            var uris = VCLib.Network.HTTPServers.HttpServiceTool.GetHttpUri(GetIPEndPoint());
            WebHttpService = new HttpService(uris);
            WebHttpService.CrossDomain = true;
            WebHttpService.HttpServiceConnectionEvent += WebHttpService_HttpServiceConnectionEvent;
            WebHttpService.Open();
        }
        public  void IPChanged(IPAddress[] iPAddresses)
        {
            this.iPAddresses = iPAddresses;
            try
            {
                WebHttpService.Dispose();
                WebHttpService = null;
                
                Thread.Sleep(5000);
                var t =Task.Run(() => {
                    Init();
                });

               t.Wait();
                VCLib.Util.LogHelp.Debug($"HTTP IP改变重新初始化成功");
            }
            catch (Exception ex)
            {
                VCLib.Util.LogHelp.Debug($"IP改变重新初始化失败：{ex.Message}");

            }

        }

        private string WebHttpService_HttpServiceConnectionEvent(object sender, VCLib.Network.HTTPServers.HttpServiceConnectionArg arg)
        {
            try
            {


                var rewUrl = arg.Request.Url.LocalPath;
                arg.Response.ContentType = VCLib.Network.HTTPServers.HttpServiceConnectionArg.JSON;
                arg.SetContentType(HttpServiceConnectionArg.JSON);
                arg.SetResponseEncoding(Encoding.UTF8);
                if (rewUrl == "/api/getDir")
                {
                    var list = new List<ListDir>();
                    foreach (var item in AppControl.Instance.ListDirs)
                    {
                        list.Add(new ListDir { FullName = item.FullName, Name = item.Name });
                    }
                    return Newtonsoft.Json.JsonConvert.SerializeObject(list);
                }
                else if (rewUrl == "/api/getFileList")
                {
                    // 使用UrlDecode进行解码
                    string decodedString = WebUtility.UrlDecode(arg.Request.Url.Query);
                  var map =  GetHttpGetArg(decodedString);
                    //var s= arg.Request.QueryString["name"];
                    if(!map.ContainsKey("dirName"))
                    {
                        arg.SetContentType(HttpServiceConnectionArg.TEXT);
                        arg.Response.StatusCode = 406;
                        return "参数错误";
                    }
                    var name = map["dirName"];
                    foreach (var item in AppControl.Instance.ListDirs)
                    {
                        if (name == item.Name)
                        {
                            var f = new List<ListFile>();
                            foreach (var j in item.ListFile)
                            {
                                f.Add(new ListFile { FullName = j.FullName, Name = j.Name, ListDirName = item.Name });
                            }
                            return Newtonsoft.Json.JsonConvert.SerializeObject(f);
                        }
                    }
                    return "[]";
                }
                else if (rewUrl == "/api/playMedia")
                {
                    // 使用UrlDecode进行解码
                    string decodedString = WebUtility.UrlDecode(arg.Request.Url.Query);
                    var map = GetHttpGetArg(decodedString);
                    //var s= arg.Request.QueryString["name"];
                    if (!map.ContainsKey("fullName"))
                    {
                        arg.SetContentType(HttpServiceConnectionArg.TEXT);
                        arg.Response.StatusCode = 406;
                        return "参数错误";
                    }
                    var name = map["fullName"];
                    if (System.IO.File.Exists(name)) 
                    {
                        AppControl.Instance.PlayCtr.Play(name);
                        return "{\"msg\":\"播放成功\"}";
                    }
                    else
                    {
                        arg.SetContentType(HttpServiceConnectionArg.TEXT);
                        arg.Response.StatusCode = 406;
                        return "文件不存在";
                    }
                  
                   
                }
                else if (rewUrl == "/api/mediaCtr")
                {
                    var action = arg.GetArgValue("action");// 0 停止 1 播放  2 暂停
                    if (action == "0")
                    {
                        AppControl.Instance.PlayCtr.Stop();
                    }
                    else if (action == "1")
                    {
                        if(!string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
                            AppControl.Instance.PlayCtr.Play();
                        else
                        {
                            arg.SetContentType(HttpServiceConnectionArg.TEXT);
                            arg.Response.StatusCode = 406;
                            return "当前没有媒体";
                        }
                    }
                    else if (action == "2")
                    {
                        AppControl.Instance.PlayCtr.Pause();
                    }
                    else if (action == "3")
                    {
                        if (AppControl.Instance.PlayStateInfo.PlayState != 0)
                        {
                            var time = arg.GetArgValue("seek");// 0 停止 1 播放  2 暂停
                            AppControl.Instance.PlayCtr.Seek(Convert.ToDouble(time));
                        }
                        else
                        {
                            arg.SetContentType(HttpServiceConnectionArg.TEXT);
                            arg.Response.StatusCode = 406;
                            return "媒体已停止";
                        }

                    }
                    else if (action == "4")
                    {
                        var vol = Convert.ToInt32(arg.GetArgValue("vol"));
                        AppControl.Instance.Volume=vol;
                        AppControl.Instance.mediaInfo.Vol = vol;
                        AppControl.Instance.mediaInfo.Update();
                    }
                    else if (action == "5")
                    {
                        if ( string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
                        {
                            //播放第一个
                            if (AppControl.Instance.ListDirs[0].ListFile.Count > 0)
                            {
                                var name = AppControl.Instance.ListDirs[0].ListFile[0].FullName;
                                if (System.IO.File.Exists(name))
                                {
                                    AppControl.Instance.PlayCtr.Play(name);
                                }
                                else 
                                {
                                    arg.SetContentType(HttpServiceConnectionArg.TEXT);
                                    arg.Response.StatusCode = 406;
                                    return "当前没有媒体";
                                }
                            }
                        }
                        else
                        {
                            var path = System.IO.Path.GetDirectoryName(AppControl.Instance.PlayStateInfo.FullName);
                            foreach (var item in AppControl.Instance.ListDirs)
                            {
                                if (item.FullName == path)
                                {
                                    for (var i = 0; i < item.ListFile.Count;i++)
                                    {
                                        if (AppControl.Instance.PlayStateInfo.FullName == item.ListFile[i].FullName)
                                        {

                                            if ((i -1) < 0)
                                            {
                                                AppControl.Instance.PlayCtr.Play(item.ListFile[item.ListFile.Count - 1].FullName);

                                            }
                                            else
                                            {
                                                AppControl.Instance.PlayCtr.Play(item.ListFile[i-1].FullName);
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }

                    }
                    else if (action == "6")
                    {
                        if (string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
                        {
                            //播放第一个
                            if (AppControl.Instance.ListDirs[0].ListFile.Count > 0)
                            {
                                var name = AppControl.Instance.ListDirs[0].ListFile[0].FullName;
                                if (System.IO.File.Exists(name))
                                {
                                    AppControl.Instance.PlayCtr.Play(name);
                                }
                                else
                                {
                                    arg.SetContentType(HttpServiceConnectionArg.TEXT);
                                    arg.Response.StatusCode = 406;
                                    return "当前没有媒体";
                                }
                            }

                        }
                        else
                        {
                            var path = System.IO.Path.GetDirectoryName(AppControl.Instance.PlayStateInfo.FullName);
                            foreach (var item in AppControl.Instance.ListDirs)
                            {
                                if (item.FullName == path)
                                {
                                    for (var i = 0; i < item.ListFile.Count; i++)
                                    {
                                        if (AppControl.Instance.PlayStateInfo.FullName == item.ListFile[i].FullName)
                                        {
                                            if ((i + 1) >= item.ListFile.Count)
                                            {
                                                AppControl.Instance.PlayCtr.Play(item.ListFile[0].FullName);
                                            }
                                            else
                                            {
                                                AppControl.Instance.PlayCtr.Play(item.ListFile[i + 1].FullName);
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    else if (action == "7")
                    {
                        var playType = Convert.ToInt32(arg.GetArgValue("PlayType"));
                        AppControl.Instance.PlayStateInfo.PlayType= playType;
                        AppControl.Instance.mediaInfo.PlayType = playType;
                        AppControl.Instance.mediaInfo.Update();
                    }
                    else if (action == "8")
                    {
                        AppControl.Instance.PlayCtr.Full(1);
                        AppControl.Instance.mediaInfo.IsFull = 1;
                        AppControl.Instance.mediaInfo.Update();
                    }
                    else if (action == "9")
                    {
                        AppControl.Instance.PlayCtr.Full(0);
                        AppControl.Instance.mediaInfo.IsFull = 0;
                        AppControl.Instance.mediaInfo.Update();
                    }
                    return "{\"msg\":\"控制成功\"}";

                }
                else if (rewUrl == "/api/getPlayState")
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(AppControl.Instance.PlayStateInfo);
                }

                arg.SetContentType(HttpServiceConnectionArg.TEXT);
                arg.Response.StatusCode = 404;
                return "未知路径";
            }
            catch (Exception ex)
            {
                arg.SetContentType(HttpServiceConnectionArg.TEXT);
                arg.Response.StatusCode = 502;
                return ex.Message;
            }
        }

        private IPEndPoint[] GetIPEndPoint()
        {
            IPEndPoint[] iPEndPoints = new IPEndPoint[iPAddresses.Length+1];
            for (int i = 0; i < iPEndPoints.Length-1; i++)
            {
                iPEndPoints[i] = new IPEndPoint(iPAddresses[i], port);
            }
            iPEndPoints[iPEndPoints.Length-1] = new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), port);
            return iPEndPoints;
        }
        private Dictionary<string,string> GetHttpGetArg(string queString)
        {
            queString = queString.TrimStart('?').Trim();
            var arr = queString.Split('=');
            Dictionary<string,string> map = new Dictionary<string,string>();
            for (int i = 0; i < arr.Length; i += 2)
            {
                map.Add(arr[i], arr[i + 1]);
            }
            return map;
        }
        ~HttpInput()
        {
            WebHttpService.Dispose();
        }
    }
}
